#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>

const std::string gdictpath = "./";
const std::string gdictname = "dict.txt";
const std::string gsep = ": ";

using namespace LogModule;

class Dictionary
{
private:
    bool SplitString(const std::string &line, std::string *key, std::string *value)
    {
        size_t pos = line.find(gsep);
        if (pos == std::string::npos) { return false; }

        *key = line.substr(0, pos);
        *value = line.substr(pos + gsep.size());
        if (key->empty() || value->empty()) { return false; }

        return true;
    }

    bool LoadDict()
    {
        // 1. 以读方式打开文件
        std::string file = _path + _name;
        std::ifstream in(file.c_str());
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open file " << file << " error";
            return false;
        }

        // 2. 读取文件
        std::string line;
        while (std::getline(in, line)) // getline读取到结束
        {
            // apple: 苹果
            std::string key;
            std::string value;
            if (SplitString(line, &key, &value))
            {
                _dict.insert(std::make_pair(key, value));
            }
        }

        in.close();

        return true;
    }

public:
    Dictionary(const std::string &path = gdictpath, const std::string &name = gdictname)
        : _path(path), _name(name)
    {
        LoadDict();
    }

    ~Dictionary() {}

    std::string Translate(const std::string &word)
    {
        auto it = _dict.find(word);
        if (it == _dict.end())
        {
            return "None";
        }
        return it->second;
    }

    void Print()
    {
        for(auto& it : _dict)
        {
            std::cout << it.first << ": " << it.second << std::endl;
        }
    }

private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _path;
    std::string _name;
};